<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>上传质量证书Word模板</span>
      </div>
      <div class="upload-container">
        <el-form ref="uploadForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="模板名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入模板名称" style="width: 400px;" />
          </el-form-item>
          <el-form-item label="模板类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择模板类型" style="width: 400px;">
              <el-option
                v-for="dict in dict.type.certificate_template_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="模板文件" prop="file" class="upload-item">
            <el-upload
              class="upload-demo"
              ref="upload"
              drag
              :action="uploadUrl"
              :headers="headers"
              :before-upload="beforeUpload"
              :on-progress="handleProgress"
              :on-success="handleSuccess"
              :on-error="handleError"
              :auto-upload="false"
              :limit="1"
              :file-list="fileList"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">
                只能上传Word文档(docx格式)，且不超过10MB。模板中可使用 ${变量名} 格式的占位符，系统将在生成证书时替换为实际数据。
              </div>
            </el-upload>
            <el-progress 
              v-if="uploadProgress > 0" 
              :percentage="uploadProgress" 
              :format="progressFormat"
              style="margin-top: 15px;"
            ></el-progress>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入模板备注信息"
              :rows="4"
              style="width: 400px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitUpload" :loading="loading">上传模板</el-button>
            <el-button @click="goBack">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 帮助说明卡片 -->
    <el-card class="box-card" style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span>模板使用说明</span>
      </div>
      <div class="help-content">
        <h4>1. 模板变量使用说明</h4>
        <p>在Word模板中，您可以使用 <code>${变量名}</code> 格式的占位符，系统会在生成证书时将其替换为实际数据。</p>
        <p>示例：<code>${productName}</code> 将被替换为产品名称。</p>
        
        <h4>2. 常用变量列表</h4>
        <el-table :data="commonVariables" border size="small" style="width: 100%">
          <el-table-column prop="name" label="变量名" width="150"></el-table-column>
          <el-table-column prop="description" label="变量描述"></el-table-column>
          <el-table-column prop="example" label="示例值" width="180"></el-table-column>
        </el-table>
        
        <h4>3. 上传后操作</h4>
        <p>模板上传成功后，您可以：</p>
        <ul>
          <li>在模板管理页面预览模板效果</li>
          <li>配置模板变量和数据源</li>
          <li>生成质量证书</li>
        </ul>
      </div>
    </el-card>
  </div>
</template>

<script>
import { uploadTemplateFile } from "@/api/qep/certificate/template";
import { getToken } from "@/utils/auth";

export default {
  name: "UploadWordTemplate",
  dicts: ['certificate_template_type'],
  data() {
    return {
      // 表单参数
      form: {
        name: undefined,
        type: undefined,
        remark: undefined
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "模板类型不能为空", trigger: "change" }
        ],
        file: [
          { required: true, message: "请选择要上传的文件", trigger: "change" }
        ]
      },
      // 上传参数
      uploadUrl: import.meta.env.VITE_APP_BASE_API + "/qep/certificate/template/upload",
      headers: { Authorization: "Bearer " + getToken() },
      fileList: [],
      loading: false,
      uploadProgress: 0,
      // 常用变量示例
      commonVariables: [
        { name: "productName", description: "产品名称", example: "高压管道" },
        { name: "productCode", description: "产品编码", example: "P001" },
        { name: "specification", description: "规格型号", example: "Φ325×28" },
        { name: "material", description: "材质", example: "12Cr1MoVG" },
        { name: "batchNo", description: "批次号", example: "XY3-01" },
        { name: "inspectionDate", description: "检验日期", example: "2024-04-30" },
        { name: "inspector", description: "检验员", example: "王小明" },
        { name: "reviewer", description: "审核人", example: "张志军" },
        { name: "reportNo", description: "报告编号", example: "UT-2024-0001" },
        { name: "conclusion", description: "检测结论", example: "合格" }
      ]
    };
  },
  methods: {
    // 提交上传
    submitUpload() {
      this.$refs.uploadForm.validate(valid => {
        if (valid) {
          if (this.$refs.upload.uploadFiles.length === 0) {
            this.$modal.msgError("请选择要上传的文件");
            return;
          }
          this.$refs.upload.submit();
        }
      });
    },
    // 上传前的校验
    beforeUpload(file) {
      // 校验文件类型
      const isDocx = file.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      if (!isDocx) {
        this.$modal.msgError("上传文件只能是Word文档(docx格式)!");
        return false;
      }
      
      // 校验文件大小
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$modal.msgError("上传文件大小不能超过10MB!");
        return false;
      }

      // 添加表单数据
      this.loading = true;
      return true;
    },
    // 上传进度
    handleProgress(event, file) {
      this.uploadProgress = Math.floor(event.percent);
    },
    // 上传成功
    handleSuccess(response, file) {
      this.loading = false;
      this.uploadProgress = 100;
      
      if (response.code === 200) {
        this.$modal.msgSuccess("模板上传成功");
        // 延迟跳转，让用户看到100%的进度
        setTimeout(() => {
          this.$router.push({ path: "/certificate/template" });
        }, 1000);
      } else {
        this.$modal.msgError("上传失败: " + (response.msg || "未知错误"));
      }
    },
    // 上传失败
    handleError(err) {
      this.loading = false;
      console.error("上传错误:", err);
      this.$modal.msgError("上传失败: " + (err.message || "服务器错误"));
    },
    // 进度格式化
    progressFormat(percentage) {
      return percentage === 100 ? '上传完成' : `${percentage}%`;
    },
    // 返回
    goBack() {
      this.$router.push({ path: "/certificate/template" });
    }
  }
};
</script>

<style scoped>
.upload-container {
  margin: 20px;
  max-width: 800px;
}

.upload-item {
  margin-bottom: 30px;
}

.help-content {
  padding: 10px;
}

.help-content h4 {
  margin-top: 15px;
  margin-bottom: 10px;
  color: #303133;
}

.help-content p {
  line-height: 1.6;
  margin-bottom: 10px;
}

.help-content ul {
  padding-left: 20px;
}

.help-content li {
  line-height: 1.8;
}

.help-content code {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 2px 6px;
  color: #E6A23C;
  font-family: monospace;
}

.el-upload-dragger {
  width: 400px;
}
</style>